#include "process/preprocess.h"
#include "utils/logging.h"

void letterbox(const cv::Mat &img, cv::Mat &img_letterbox, letterbox_t &letter_box, uint32_t width, uint32_t height)
{
    if(img.channels()!=3)
    {
        NN_LOG_ERROR("img has to be 3 channels");
        exit(-1);
    }

    int orig_img_width  = img.cols;
    int orig_img_height = img.rows;
    int dst_width;
    int dst_height;

    if (orig_img_width >= orig_img_height)
    {
        dst_width = orig_img_width;
        dst_height = orig_img_width;
    }
    else if (orig_img_width < orig_img_height)
    {
        dst_height = orig_img_height;
        dst_width = orig_img_height;
    }

    float scale = 1.0;
    float _scale_w = (float)width / orig_img_width;
    float _scale_h = (float)height / orig_img_height;
    if(_scale_w < _scale_h) {
        scale = _scale_w;
    } else {
        scale = _scale_h;
    }

    int x_padding = dst_width - orig_img_width;
    int y_padding = dst_height - orig_img_height;

    int _left_offset = x_padding / 2.f;
    int _top_offset = y_padding / 2.f;
  

    //set offset and scale
    letter_box.scale = scale;
    letter_box.x_pad = _left_offset;
    letter_box.y_pad = _top_offset;



    /*
     * Padding an image.
                                    dst_img
        --------------      ----------------------------
        |            |      |       top_border         |
        |  src_image |  =>  |                          |
        |            |      |      --------------      |
        --------------      |left_ |            |right_|
                            |border|  dst_rect  |border|
                            |      |            |      |
                            |      --------------      |
                            |       bottom_border      |
                            ----------------------------
     */
    // 使用cv::copyMakeBorder函数进行填充边界
    cv::copyMakeBorder(img, img_letterbox, _top_offset, _top_offset, _left_offset, _left_offset, cv::BORDER_CONSTANT, cv::Scalar(0, 0, 0));
}

void cvimg2tensor(const cv::Mat &img, uint32_t width, uint32_t height, tensor_data_s &tensor)
{
    if(img.channels()!=3)
    {
        NN_LOG_ERROR("img has to be 3 channels");
        exit(-1);
    }

    /*BGR 2 RGB*/
    cv::Mat img_rgb;
    cv::cvtColor(img, img_rgb, cv::COLOR_BGR2RGB);
    cv::Mat img_resized;
    cv::resize(img_rgb, img_resized, cv::Size(width, height), 0, 0, cv::INTER_LINEAR);
    // cv::imwrite("img_letterbox.jpg", img_resized);

    memcpy(tensor.data, img_resized.data, tensor.attr.size);
}
